<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .slider-box{
            border: 1px solid black;
            position: relative;
            height: 40px;
            width: 400px;
        }
        .slider-line{
            position: absolute;
            width: 360px;
            height: 6px;
            background-color: grey;
            left: 20px;
            top: 17px;
        }
        .slider-point{
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: radial-gradient(white,black);
            top: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <slider :volume='volume' @vol-change='getVol'></slider>
        <p>当前音量：{{volume}}</p>
    </div>
    <script src='vue.js'></script>

    <script type="text/html" id="slider">
        <div class='slider-box'@mousedown='mousedown' @mousemove='mousemove'>
            <div class="slider-line"></div>
            <div class="slider-point" :style='pointStyle'></div>
        </div>
        
    </script>

    <script>
        Vue.component('slider',{
            template:'#slider',
            props:{
                volume:{ // props验证
                    default:0.5,
                    type:Number,
                }
            },
            data:function() {  
                    return {
                        isdown:false,
                    }
            },
            computed:{
                pointStyle(){
                    var left = 360*this.volume+20
                    left = left<20?20:left
                    left = left>380?380:left
                    return {
                        left:left -10 + 'px'
                    }
                }
            },
            methods:{
                mousedown(e){
                    // 组件对象的$el属性表示组件的根元素
                    // console.log(this.$el)
                    this.isdown = true
                    var x = e.pageX - this.$el.offsetLeft
                    this.$emit('vol-change',(x-20)/360)
                },
                mousemove(e){
                    if(this.isdown){
                        var x = e.pageX - this.$el.offsetLeft
                        this.$emit('vol-change',(x-20)/360)
                    }
                },
                mouseup(e){
                    this.isdown = false
                }
            },
            mounted:function(){
                window.addEventListener('mousemove',this.mousemove.bind(this))
                window.addEventListener('mouseup',this.mouseup.bind(this))
            }
        })
        var app = new Vue({
            el:'#app',
            data:{
                volume:0.7
            },
            methods:{
                getVol(e){
                    console.log(e)
                    this.volume = e
                }
            }
        })
    </script>
</body>
</html>